<?php

namespace frontend\modules\Api\controllers;

use common\services\QuestionService;
use Exception;
use Yii;
use yii\base\DynamicModel;
use yii\base\ExitException;
use yii\base\InvalidConfigException;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;

class QuestionController extends ApiController
{
    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }


    /**
     * @throws ExitException
     * @throws InvalidConfigException
     */
    public function actionAdd(){
        $form = DynamicModel::validateData([
            'question_text' => Yii::$app->getRequest()->post('question_text'),
            'question_user_info' => Yii::$app->getRequest()->post('question_user_info'),
            'user_id'=>$this->_user['id'],
            'imgs'=>Yii::$app->getRequest()->post('imgs','')
        ],[
            [['question_text','question_user_info'], 'required'],
            ['question_text', 'filter', 'filter' => 'trim'],
            ['question_text', 'string','min'=> 1]
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }
        $result = QuestionService::create(ArrayHelper::toArray($form));
        if(!$result){
            throw new Exception(QuestionService::getError());
        }
        return self::successResponse(['id'=>$result]);
    }


    public function actionLists(){
        $condition = Yii::$app->request->get(); // type 等参数
        $list = QuestionService::getList($condition);
        return self::successResponse($list);
    }



}